using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using PlayerIOClient;

/**
A class representing the state of the Factory for the user
It's supposed to be updated as part of the game update
*/
public class GameFactory : MonoBehaviour {
	//holds the state of the game
	public static GameFactory instance;
	
	public int level;
	public List<string> units;
	public bool isLoaded;
	
	DatabaseObject factoryObj;
	
	void Awake() {
		if (instance == null) {
			instance = this;
		}
		else
			enabled = false;
	}
	
	void Start() {
		Debug.Log("GameFactory.Start");
		if (GameClient.instance != null) {
			Debug.Log("GameFactory.PlayerObjectLoaded : subscribed");
			GameClient.instance.PlayerObjectLoaded += OnPlayerObjectLoaded;
		}
		else
			Load();
	}
	
	void Update() {
		//advance the production queue
	}
	
	// get my data from player object
	void OnPlayerObjectLoaded(DatabaseObject playerObj) {
		//Debug.Log("GameFactory.OnPlayerObjectLoaded : " + playerObj);
		factoryObj = playerObj.GetObject("Factory");
		if (factoryObj != null) {
			//Debug.Log("GameFactory.OnPlayerObjectLoaded : Loading factory...");
			level = factoryObj.GetInt("level");
			DatabaseArray unitsObj = factoryObj.GetArray("units");
			if (unitsObj != null) {
				//Debug.Log("GameFactory.OnPlayerObjectLoaded : Units.Count=" + unitsObj.Count);
				for (int i=0; i<unitsObj.Count; i++)
					units.Add(unitsObj.GetString(i));
			}
		}
		else {
			//Debug.Log("GameFactory.OnPlayerObjectLoaded : Creating factory...");
			factoryObj = new DatabaseObject();
			factoryObj.Set("level", level);
			playerObj.Set("Factory", factoryObj);
			playerObj.Save();
		}
		
		isLoaded = true;
	}
	
	// load from local file
	void Load() {
	}
	
	//save to local file
	void Save() {
	}
	
	// load from persistence
	void Initialize() {
		//load from remote game state:
		//factory level
		//units unlocked
		//units produced
		//production queue (time finish)
	}
	
	// produce unit
	public void AddUnit(string unitId) {
		//get unit data from GameData
		Debug.Log("GameFactory.AddUnit : unit=" + unitId);
		
		DatabaseArray unitsObj = factoryObj.GetArray("units");
		if (unitsObj==null) {
			unitsObj = new DatabaseArray();
			factoryObj.Set("units", unitsObj);
		}
		
		unitsObj.Add(unitId);
		GameClient.instance.SavePlayerObject();
	}
}
